package com.pucong.gitee.database.backup.business.database.service;

import com.pucong.gitee.database.backup.common.entity.database.AutoDataSource;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.business.database.mapper.AutoDataSourceMapper;
import com.pucong.gitee.database.backup.business.database.mapper.AutoExeSqlLogMapper;
import com.pucong.gitee.database.backup.business.database.util.OperationService;
import com.pucong.gitee.database.backup.business.database.util.BackupServiceFactory;
import com.pucong.gitee.database.backup.utils.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseStaticServiceImpl implements DatabaseStaticService {

    @Autowired
    private AutoDataSourceMapper autoDataSourceMapper;

    @Autowired
    private AutoExeSqlLogMapper autoExeSqlLogMapper;

    @Autowired
    private BackupServiceFactory backupServiceFactory;

    @Override
    public OperationService getConnectionById(String sessionId, String dataSourceId, String databaseName, String schemaName){
        if(StringUtils.isBlank(sessionId)){
            sessionId = dataSourceId + "_" + UUID.uuid();
        }
        AutoDataSource autoDataSource = autoDataSourceMapper.selectById(dataSourceId);
        if(autoDataSource == null){
            throw new BusinessException("获取数据库异常，未找到数据源");
        }
        OperationService operationService = backupServiceFactory.getBackupService(autoDataSource, autoExeSqlLogMapper);
        operationService.setSessionId(sessionId);
        operationService.setDataBase(databaseName);
        operationService.setSchema(schemaName);
        Boolean connection = operationService.getConnection();
        if(!connection){
            throw new BusinessException("数据库连接失败");
        }
        return operationService;
    }
}
